import logging
import sys
import os
from datetime import datetime
from pytz import timezone
from logging.handlers import TimedRotatingFileHandler

root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
tz = timezone('Asia/Shanghai') # UTC, Asia/Shanghai, Europe/Berlin

def timetz(*args):
    return datetime.now(tz).timetuple()


DATE_FORMAT = '%Y-%m-%d %H:%M:%S'

def stdout_logging():
    # Set custom logger
    # 设置日志格式
    formatter = logging.Formatter(
        fmt="%(asctime)s [%(levelname)-5s] %(message)s",
        datefmt=DATE_FORMAT,
    )

    formatter.converter = timetz

    main_logger = logging.getLogger('stdout')
    main_logger.setLevel(logging.DEBUG)
    # 日志在屏幕上输出
    stdoutHandler = logging.StreamHandler(sys.stdout)
    stdoutHandler.setFormatter(formatter)
    # stdoutHandler.setLevel(logging.DEBUG)

    # 日志保存在文件
    # fileHandler = logging.FileHandler(LOG_PATH, encoding='UTF-8')
    # fileHandler.setLevel(logging.INFO)
    # fileHandler.setFormatter(formatter)
    if not main_logger.handlers:
        main_logger.addHandler(stdoutHandler)
    # main_logger.addHandler(fileHandler)

    return main_logger



def json_logging():
    LOG_PATH = os.path.join(root_path, 'logs', 'json.log')

    # 设置日志格式
    formatter = logging.Formatter(
        "%(message)s"
    )

    main_logger = logging.getLogger('json')
    main_logger.setLevel(logging.INFO)

    # 日志保存在文件
    # fileHandler = logging.FileHandler(LOG_PATH, encoding='UTF-8')
    fileHandler = TimedRotatingFileHandler(LOG_PATH, when="midnight",  interval=1, backupCount=7)
    fileHandler.setFormatter(formatter)
    fileHandler.suffix="%Y%m%d"
 
    main_logger.addHandler(fileHandler)

    return main_logger

# Do it when this module is loaded
logger = stdout_logging()

json_logger = json_logging()